package ru.yermak.bookkeeping.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Property;
import org.hibernate.Criteria;
import ru.yermak.bookkeeping.model.Group;
import ru.yermak.bookkeeping.model.User;

import java.util.List;

/**
 * User: harrier
 * Date: Aug 12, 2008
 */
@Repository
public class HibernateUserDao implements UserDao {
    private HibernateTemplate hibernateTemplate;


    public Group getGroupByUserId(Integer userId) {
        User user = (User) hibernateTemplate.load(User.class, userId);
        return user.getGroup();
    }

    public Group getGroupById(Integer groupId) {
        return (Group) hibernateTemplate.load(Group.class, groupId);
    }

    @Override
    public User getUserByLogin(String login) {
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class).add(Property.forName("login").eq(login));
        List userList = hibernateTemplate.findByCriteria(criteria, 0, 1);
        if (userList.isEmpty()) {
            return null;
        }
        return (User) userList.get(0);
    }

    @Override
    public Integer saveGroup(Group group) {
        return (Integer) hibernateTemplate.save(group);
    }

    @Override
    public Integer saveUser(User user) {
        return (Integer) hibernateTemplate.save(user);
    }

    @Override
    public User getUserById(Integer userId) {
        return (User) hibernateTemplate.load(User.class, userId);
    }

    @Autowired
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
}
